package com.tianyu.service.schedule;

import com.alibaba.fastjson2.JSON;
import com.tianyu.service.cache.DataCacheService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.config.IntervalTask;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;

import java.lang.management.ManagementFactory;
import java.time.Duration;
import java.util.ArrayList;
import java.util.concurrent.ThreadPoolExecutor;

import static com.tianyu.service.cache.DataCacheService.*;

/**********************************
 * @Author YSW
 * @Description 定时任务配置
 * @Date 2023/7/20 - 19:03
 **********************************/

@Slf4j
@Configuration
@EnableScheduling
public class ScheduleTaskService implements SchedulingConfigurer {

    @Bean
    public TaskScheduler taskScheduler() {
        ThreadPoolTaskScheduler executor = new ThreadPoolTaskScheduler();
        executor.setPoolSize(3);
        executor.setThreadNamePrefix("scheduling-");
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.initialize();
        return executor;
    }

    @Override
    public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
        scheduledTaskRegistrar.setTaskScheduler(taskScheduler());
        scheduledTaskRegistrar.addFixedRateTask(new IntervalTask(this::logs, Duration.ofSeconds(120), Duration.ofSeconds(5)));
    }


    /**
     * 定时打印日志
     */
    @Async
    protected void logs() {
        log.info("DOCK: [{}] => {}, Total Threads: {}",
                DataCacheService.dockOsdMap.size(),
                JSON.toJSONString(DataCacheService.dockOsdMap.keySet().stream().toList()),
                ManagementFactory.getThreadMXBean().getThreadCount());
    }

}
